
import { isIOS } from './app'

let elementStyle = document.createElement('div').style

export const trimAll = function(string) {
  return (string || '').replace(/[\s\uFEFF]/g, '')
}

let vendor = (() => {
  let transformNames = {
    webkit: 'webkitTransform',
    Moz: 'MozTransform',
    O: 'OTransform',
    ms: 'msTransform',
    standard: 'transform'
  }

  for (let key in transformNames) {
    if (elementStyle[transformNames[key]] !== undefined) {
      return key
    }
  }

  return false
})()

export function prefixStyle(style) {
  if (vendor === false) {
    return false
  }

  if (vendor === 'standard') {
    return style
  }

  return vendor + style.charAt(0).toUpperCase() + style.substr(1)
}

function _transform(options) {
  var y = 0
  var wrapperEl = options.wrapper
  if (!options.type) {
    y = options.parent.getBoundingClientRect().top - options.delta + (parseInt(wrapperEl.getAttribute('data-transform-y')) || 0)
  }
  wrapperEl.style['-webkit-transition'] = 'all 0.2s'
  wrapperEl.style['transition'] = 'all 0.2s'
  wrapperEl.style['transform'] = 'translate3d(0,-' + y + 'px,0)'
  wrapperEl.style['-webkit-transform'] = 'translate3d(0,-' + y + 'px,0)'
  wrapperEl.setAttribute('data-transform-y', y)

  function _touchmoveHander(e) {
    options.el &&
      scrollIntoOriginal({
        wrapper: options.wrapper
      })

    options.el && options.el.blur()
    window.removeEventListener('touchmove', _touchmoveHander)
  }
  window.addEventListener('touchmove', _touchmoveHander)
  var winHeight = window.innerHeight
  window.addEventListener('resize', function() {
    if (window.innerHeight < winHeight) {
      winHeight = window.innerHeight
    } else {
      _touchmoveHander.call()
      winHeight = window.innerHeight
    }
  })
}

export function scrollIntoTop(options) {
  if (isIOS()) return
  _transform(options)
}

export function scrollIntoOriginal(options) {
  if (isIOS()) return
  options = Object.assign(
    {
      type: 1
    },
    options
  )
  _transform(options)
}

export function addClass(el, className) {
  if (hasClass(el, className)) {
    return
  }

  let newClass = el.className.split(' ')
  newClass.push(className)
  el.className = newClass.join(' ')
}

export function removeClass(el, className) {
  if (hasClass(el, className)) {
    let newClass = el.className.split(' ')
    let index = newClass.indexOf(className)
    if (index > -1) {
      newClass.splice(index, 1)
    }
    el.className = newClass
  }
}

